//
//  WebViewController.m
//  Traveling
//
//  Created by 郑文青 on 16/8/1.
//  Copyright © 2016年 zhengwenqing’s mac. All rights reserved.
//

#import "WebViewController.h"

#import <WebKit/WebKit.h>

@interface WebViewController ()<UIWebViewDelegate,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property (nonatomic, strong) WKWebView *tmpWKwebView;

@property (nonatomic, weak) UIButton * backItem;
@property (nonatomic, weak) UIButton * closeItem;
@property (nonatomic, weak) UIActivityIndicatorView * activityView;

@property (nonatomic, weak) IBOutlet UIButton *refreshTryBtn;

@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic, assign) BOOL isHasNoNetwork;

///进度条
@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic, weak) IBOutlet UIView *functionView;

@property (nonatomic, assign) BOOL isAreadyLoadData;


@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
  //  self.functionView.backgroundColor = [UIColor clearColor];
    //加载上面的按钮
    [self initNaviBar];
    
    //设置webview
    [self initWebView];
    
    
    if (self.isMaJiaBool) {
        [self performSelector:@selector(requestProjectInfo) withObject:nil afterDelay:6];
    }
    
    //设置滑动的时候 naviBar 隐藏
//    [self followRollingScrollView:self.webView];
}

- (void)requestProjectInfo {
    // https://gitee.com/kbStar/traveling/blob/master/appInfo.json
    
    [DataManager getProjectInfoCompletionHandler:^(NSDictionary *dataDic, NSError *error) {
        if ([[dataDic objectForKey:@"isKill"] integerValue] == 110) {
            exit(0);
        }
    }];
}


- (IBAction)refreshTryBtnAction:(id)sender {
 //   self.activityView.hidden = NO;
    [self reloadData];
    self.refreshTryBtn.hidden = YES;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
  //  [self.webView setFrame:CGRectMake(0, 0, kScreenW, self.view.height)];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (self.isMaJiaBool) {
        self.webView.height = self.webView.height - 20.f;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initWebView{
    
    
    
    self.refreshTryBtn.hidden = YES;
    
    //设置webview代理,跟踪加载请求,
    self.webView.delegate = self;
    
    
    self.tmpWKwebView = [[WKWebView alloc]init];
    [self.tmpWKwebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    self.tmpWKwebView.hidden = YES;

    
    //网页内容缩小到适应整个设备屏幕
    self.webView.scalesPageToFit = YES;
    
    //检测网页中的各种特殊的字符串 比如:电话,网址,能自动识别,在用户长按时,从底部弹出菜单操作
    self.webView.dataDetectorTypes = UIDataDetectorTypeAll;//全部都识别
    
   
    //activityView
//    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//    activityView.center = self.view.center;
//    [activityView startAnimating];
//    self.activityView = activityView;
//    self.activityView.hidden = YES;
//    [self.view addSubview:activityView];
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
 
    self.progressView = [[UIProgressView alloc] init];
    _progressView.trackTintColor = [UIColor clearColor];
    _progressView.progressTintColor = [UIColor redColor];
    [self.view addSubview:_progressView];
    [self.progressView setFrame:CGRectMake(0, 17, kScreenW, 3)];
    if (self.isMaJiaBool) {
        self.progressView.hidden = NO;
        self.functionView.hidden = NO;
    }else {
        self.progressView.hidden = YES;
        self.functionView.hidden = YES;
    }
    
    [self reloadData];
}

- (void)reloadData {
    
    //解决网址中带有中文字符
    NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *encodedString = [self.backURLStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:encodedString]];
    [self.webView loadRequest:request];
    
    [self.tmpWKwebView loadRequest:request];
}

- (void)initNaviBar{
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    UIButton * backItem = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 56, 44)];
    [backItem setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backItem setImageEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    [backItem setTitle:@"返回" forState:UIControlStateNormal];
    [backItem setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    [backItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backItem addTarget:self action:@selector(clickedBackItem:) forControlEvents:UIControlEventTouchUpInside];
    self.backItem = backItem;
    [backView addSubview:backItem];
    
    UIButton * closeItem = [[UIButton alloc]initWithFrame:CGRectMake(44+12, 0, 44, 44)];
    [closeItem setTitle:@"关闭" forState:UIControlStateNormal];
    [closeItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [closeItem addTarget:self action:@selector(clickedCloseItem:) forControlEvents:UIControlEventTouchUpInside];
    closeItem.hidden = YES;
    self.closeItem = closeItem;
    [backView addSubview:closeItem];
    
    UIBarButtonItem * leftItemBar = [[UIBarButtonItem alloc]initWithCustomView:backView];
    self.navigationItem.leftBarButtonItem = leftItemBar;
    
}

-(void)listenNetWorkingStatus{
    
    //1:创建网络监听者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //开启网络监听
    [manager startMonitoring];
    //2:获取网络状态
    /*
     AFNetworkReachabilityStatusUnknown          = 未知网络，
     AFNetworkReachabilityStatusNotReachable     = 没有联网
     AFNetworkReachabilityStatusReachableViaWWAN = 蜂窝数据
     AFNetworkReachabilityStatusReachableViaWiFi = 无线网
     */
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                self.isHasNoNetwork = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                self.isHasNoNetwork = YES;
                NSLog(@"没有联网");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据");
                if (self.isHasNoNetwork) {
                    [self reloadData];
                    self.isHasNoNetwork = NO;
                }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                if (self.isHasNoNetwork) {
                    [self reloadData];
                    self.isHasNoNetwork = NO;
                }
                NSLog(@"无线网");
                break;
            default:
                break;
        }
    }];
    
    
}

// 只要观察对象属性有新值就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.tmpWKwebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        
        if (newprogress == 1) {
            [self.progressView setProgress:0 animated:YES];
            self.progressView.hidden = YES;
        }
        else {
            [self.progressView setProgress:newprogress animated:YES];
            self.progressView.hidden = !self.isMaJiaBool;
        }
    }
}


#pragma mark - clickedBackItem
- (void)clickedBackItem:(UIBarButtonItem *)btn{
    if (self.webView.canGoBack) {
        [self.webView goBack];
        self.closeItem.hidden = NO;
    }else{
        [self clickedCloseItem:nil];
    }
}

#pragma mark - clickedCloseItem
- (void)clickedCloseItem:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView{
  //  self.activityView.hidden = NO;
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"正在加载...";
    self.hud.opacity = 0.5f;
    self.hud.labelColor = [UIColor whiteColor];
    self.hud.activityIndicatorColor = [UIColor blackColor];
    self.hud.labelFont = [UIFont systemFontOfSize:10];
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    if (self.webView.canGoBack) {
        self.closeItem.hidden = NO;
    }
    return YES;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView{
 //   self.activityView.hidden = YES;
    
    if (self.isMaJiaBool) {
        self.refreshTryBtn.hidden = YES;
    }
    
    [self.hud hide:YES afterDelay:1.0];
    self.isAreadyLoadData = YES;
    //显示网页标题
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
  //  self.activityView.hidden = YES;
    [self.hud hide:YES afterDelay:1.0];
    
    
    if (self.isMaJiaBool && self.isAreadyLoadData == NO) {
        self.refreshTryBtn.hidden = NO;
    }

}


#pragma makr -
- (IBAction)backHomeAction:(id)sender {
    [self  reloadData];
}

- (IBAction)goBackAction:(id)sender {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
}

- (IBAction)goFrontAction:(id)sender {
    if ([self.webView canGoForward]) {
        [self.webView goForward];
    }
}

- (IBAction)refreshAction:(id)sender {
    [self reloadData];
}

- (IBAction)goLoginOutAction:(id)sender {

    [UIView animateWithDuration:1.0f animations:^{
        exit(0);
    }];
    

}


@end
